import 'dart:async';

import 'package:flutter/material.dart';
import 'package:t_mb_03/file.dart';
import 'package:t_mb_03/get_http.dart';
import 'package:t_mb_03/xq.dart';

Timer? time_timer;
bool time_flag = false;

String zf(int word_count) {
  double k_count = word_count / 1000;
  double w_count = word_count / 10000;
  if (word_count < 1000) {
    return word_count.toString();
  } else if (word_count < 10000) {
    bool int_flag = k_count.truncateToDouble() == k_count;
    return "${k_count.toStringAsFixed(int_flag ? 0 : 1)}k";
  } else {
    bool int_flag = w_count.truncateToDouble() == w_count;
    return "${w_count.toStringAsFixed(int_flag ? 0 : 1)}w";
  }
}

class menu_home extends StatefulWidget {
  const menu_home({super.key});

  @override
  State<menu_home> createState() => _menu_homeState();
}

class _menu_homeState extends State<menu_home> {
  var form_key = GlobalKey<FormState>();
  int current_index = 0;
  int read_target = 5;
  late int read_jd = 0;
  var to_day = DateTime.now();
  int time_count = 0;
  var l = [];
  var save_list = [];

  void start_timer() {
    time_timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (read_jd - time_count <= 0) {
        time_flag = false;
        time_timer?.cancel();
      } else {
        time_count += 1;
      }
      setState(() {});
    });
  }

  void stop_timer() {
    time_timer?.cancel();
  }

  void show_setting_page() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("设置阅读目标"),
          content: Form(
            key: form_key,
            child: Container(
              decoration: BoxDecoration(border: Border.all(color: Colors.cyan)),
              child: TextFormField(
                onSaved: (value) {
                  read_target = int.parse(value!);
                },
                validator: (value) {
                  if (value!.isEmpty) {
                    return "为空";
                  }
                  if (value.contains("-") && value.contains(".")) {
                    return "阅读目标时间只能为大于 0 的整数";
                  }
                  return null;
                },
                decoration: InputDecoration(
                  hintText: "阅读目标时间",
                  border: InputBorder.none,
                ),
              ),
            ),
          ),
          actions: [
            ElevatedButton(
              onPressed: () {
                if (form_key.currentState!.validate()) {
                  form_key.currentState!.save();
                  read_jd = read_target * 60;
                  time_count = 0;
                  save_to_day_file(to_day.day, read_target);
                  Navigator.pop(context);
                }
                setState(() {});
              },
              child: Text("确定按钮"),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
                setState(() {});
              },
              child: Text("取消按钮"),
            ),
          ],
        );
      },
    );
  }

  void get_http() async {
    await API.get_book_list_api();
  }

  @override
  void initState() {
    // TODO: implement initState
    get_http();
    l = read_to_day_file();
    if (l[0] == to_day.day) {
      read_target = l[1];
      read_jd = read_target * 60;
    } else {
      save_to_day_file(to_day.day, read_target);
    }
    save_list = read_sj_file().values.toList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    API.book_list.sort((a, b) => a["publish_date"].compareTo(b["publish_date"]));
    save_list = read_sj_file().values.toList();
    return Scaffold(
      body: DefaultTextStyle(
        style: TextStyle(fontSize: 30, color: Colors.black),
        child: SingleChildScrollView(
          child: Row(
            children: [
              Container(
                width: 350,
                height: MediaQuery.of(context).size.height,
                color: Colors.grey.shade400,
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "每日阅读",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 40),
                      ),
                      InkWell(
                        onTap: () {
                          current_index = 0;
                          setState(() {});
                        },
                        child: Container(
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: current_index == 0
                                  ? Colors.white
                                  : Colors.grey,
                              border: Border.all(color: Colors.grey)),
                          child: Text("首页"),
                        ),
                      ),
                      Text(
                        "书库",
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      InkWell(
                        onTap: () {
                          current_index = 1;
                          setState(() {});
                        },
                        child: Container(
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: current_index == 1
                                  ? Colors.white
                                  : Colors.grey,
                              border: Border.all(color: Colors.grey)),
                          child: Text("选新书"),
                        ),
                      ),
                      Text(
                        "我的藏书",
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      InkWell(
                        onTap: () {
                          current_index = 2;
                          setState(() {});
                        },
                        child: Container(
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: current_index == 2
                                  ? Colors.white
                                  : Colors.grey,
                              border: Border.all(color: Colors.grey)),
                          child: Text("书架"),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              if (current_index == 0) page0(context),
              if (current_index == 1) page1(context),
              if (current_index == 2) page2(context),
            ],
          ),
        ),
      ),
    );
  }

  Expanded page2(BuildContext context) {
    return Expanded(
      child: Container(
        height: MediaQuery.of(context).size.height,
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            children: [
              Row(
                children: [
                  Text("书架"),
                ],
              ),
              Divider(
                thickness: 5,
              ),
              Expanded(
                child: GridView.builder(
                  padding: EdgeInsets.symmetric(horizontal: 80, vertical: 24),
                  itemCount: save_list.length,
                  shrinkWrap: true,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3,
                    mainAxisSpacing: 50,
                    mainAxisExtent: 350,
                    crossAxisSpacing: 20
                  ),
                  itemBuilder: (BuildContext context, int index) {
                    var v = save_list[index];
                    return InkWell(
                      onTap: () async {
                        String book_id = v[0];
                        await API.get_xp_dic_api(book_id);
                        await API.get_music_url_api(book_id);
                        if (time_flag == false) {
                          start_timer();
                          time_flag = true;
                        }
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => xq_home()));
                        setState(() {});
                      },
                      child: Container(
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey),
                        ),
                        child: Column(
                          children: [
                            Container(
                              margin: EdgeInsets.all(8),
                              width: 120,
                              height: 160,
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  image: NetworkImage(
                                      "${API.ip}/images/${v[2]}"),
                                ),
                              ),
                            ),
                            Text("${v[1]}"),
                            Text("${v[3]}"),
                            Text("已阅读时间:${(v[4] % 3600) ~/ 60}分钟", style: TextStyle(fontSize: 24),),
                            Text("已阅读进度:${v[5] == v[6] ? "已完成" : "${zf(v[5])}/${zf(v[6])}"}", style: TextStyle(fontSize: 24),),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Expanded page1(BuildContext context) {
    return Expanded(
      child: Container(
        height: MediaQuery.of(context).size.height,
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            children: [
              Row(
                children: [
                  Text("选新书"),
                ],
              ),
              Divider(
                thickness: 5,
              ),
              DefaultTextStyle(
                style: TextStyle(fontSize: 25, color: Colors.grey),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Text("封面"),
                    Text("标题"),
                    Text("作者"),
                    Text("出版日期"),
                    Text("字数"),
                    Text("  "),
                  ],
                ),
              ),
              Expanded(
                child: ListView(
                  shrinkWrap: true,
                  children: [
                    for (int i = 0; i < API.book_list.length; i++)
                      Container(
                        margin: EdgeInsets.symmetric(vertical: 12),
                        decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey)),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Container(
                              margin: EdgeInsets.all(8),
                              width: 120,
                              height: 160,
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  image: NetworkImage(
                                      "${API.ip}/images/${API.book_list[i]["cover_image"]}"),
                                ),
                              ),
                            ),
                            Text("${API.book_list[i]["title"]}"),
                            Text("${API.book_list[i]["author_name"]}"),
                            Text("${API.book_list[i]["publish_date"]}"),
                            Text("${zf(API.book_list[i]["word_count"])}"),
                            InkWell(
                              onTap: () async {
                                String book_id = API.book_list[i]["id"];
                                await API.get_xp_dic_api(book_id);
                                await API.get_music_url_api(book_id);
                                if (time_flag == false) {
                                  start_timer();
                                  time_flag = true;
                                }
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => xq_home()));
                                setState(() {});
                              },
                              child: Container(
                                width: 150,
                                height: 50,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    color: Colors.white,
                                    border: Border.all(color: Colors.grey)),
                                child: Text("开始阅读"),
                              ),
                            ),
                          ],
                        ),
                      ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Expanded page0(BuildContext context) {
    return Expanded(
      child: Container(
        height: MediaQuery.of(context).size.height,
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            children: [
              Row(
                children: [
                  Text("${to_day.month}月${to_day.day}日，今日阅读"),
                ],
              ),
              Stack(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text("我的阅读目标"),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      ElevatedButton(
                        onPressed: () {
                          show_setting_page();
                          setState(() {});
                        },
                        style: ElevatedButton.styleFrom(
                            side: BorderSide(color: Colors.grey),
                            shape: RoundedRectangleBorder(),
                            backgroundColor: Colors.white),
                        child: Text(
                          "设置",
                          style: TextStyle(color: Colors.black),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "${read_target}分钟",
                    style: TextStyle(color: Colors.blue),
                  ),
                ],
              ),
              SizedBox(
                height: 40,
              ),
              Stack(
                alignment: Alignment.center,
                children: [
                  Container(
                    width: 450,
                    height: 450,
                    child: CircularProgressIndicator(
                      value: read_jd <= 0 ? 1 : time_count / read_jd,
                      strokeWidth: 15,
                      backgroundColor: Colors.grey,
                      color: Colors.blueAccent,
                    ),
                  ),
                  Column(
                    children: [
                      Text("今日阅读进度"),
                      Text(
                        "${((read_jd - time_count % 3600) ~/ 60).toString().padLeft(2, "0")}:${((read_jd - time_count) % 60).toString().padLeft(2, "0")}",
                        style:
                            TextStyle(color: Colors.blueAccent, fontSize: 70),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
